;(function(){

    var option = {
        'type':'pic',    //默认上传文件类型，type:pic  或者 ‘file’
        'multiple':false,    //是否多张图上传
        'max':9,    //只有multiple为true时需要配置且生效。
        'maxSize': 10 * 1024 * 1024,    //单张图最大支持10M。
        'limit': []  // 文件类型限制, 后缀名数组, eg: ['jpg', 'png']
    };

    function Upload(){

    }

    function getPromptCss(){
        $.ajax({
            type:"get",
            url:"/javascripts/widget/prompt/prompt.css",
            success:function(res){
                var styleEle = document.createElement("style");
                styleEle.innerHTML = res;
                $("head")[0].appendChild(styleEle);
            }
        });
    }

    Upload.prototype.init = function(config){
        var _this = this;

        _this.opts = $.extend({}, option, config);

        _this.selector = $(_this.opts.selector);

        _this.initialize();

        _this.handle();

        getPromptCss();

        return _this;
    };

    /**
     * 初始化图片展示
     */
    Upload.prototype.initialize = function(){
        var _this = this;

        if(!_this.opts.data || (typeof _this.opts.data != 'object') ){ return; }

        if(_this.opts.data.length){    //多组图片，data为数组对象。
            for(var i=0,l=_this.opts.data.length; i<l; i++){
                _this.redom(_this.opts.data[i]);
            }
        }else{    //单张图片，data为对象
            _this.redom(_this.opts.data);
        }
        _this.updateStatus();
    };

    /**
     * 事件绑定
     */
    Upload.prototype.handle = function(){
        var _this = this;

        _this.selector.find('.upload-input-file').bind('change', function(event){
            
            if(_this.opts.callback && (typeof _this.opts.callback == 'function')){    //在执行上传请求之前执行的回调
                _this.opts.callback();
            }

            var filesArr = [];

            if(_this.opts.multiple){
                for(var i=0, l=$(this)[0].files.length; i<l; i++){
                    filesArr.push($(this)[0].files[i]);
                }

                var totalNum = filesArr.length + _this.uploadedNum();

                if(totalNum > _this.opts.max){

                    _this.alerts({msg:'最多支持上传'+ _this.opts.max + '张图片！'});
                    return;
                }
            }else{
                var file = (event.srcElement || event.target).files[0];
                filesArr.push(file);
            }
            _this.uploadFile(filesArr);
        });

        //鼠标移动到图片
        _this.hovers();

        //图片删除
        _this.deletes();

        //图片预览
        _this.enlarge();
    };

    /**
     * 鼠标移动到图片上面事件
     */
    Upload.prototype.hovers = function(){
        var _this = this;

        if(_this.opts.multiple){
            _this.selector.delegate('.upload-img-list', 'mouseover', function(){
                $(this).addClass('open');
            });
            _this.selector.delegate('.upload-img-list', 'mouseout', function(){
                $(this).removeClass('open');
            });
        }else{
            _this.selector.delegate('.upload-btn-box', 'mouseover', function(){
                $(this).addClass('open');
            });
            _this.selector.delegate('.upload-btn-box', 'mouseout', function(){
                $(this).removeClass('open');
            });
        }
    };

    /**
     * 删除图片
     */
    Upload.prototype.deletes = function(){
        var _this = this;

        _this.selector.delegate('.upload-del', 'click', function(event){
            $(this).parent('.upload-img-list').remove();

            _this.updateStatus();

            event.stopPropagation();
        });
    };

    /**
     * 图片预览
     */
    Upload.prototype.enlarge = function(){
        var _this = this;

        if(!_this.opts.multiple){
            return;
        }

        _this.selector.delegate('.upload-img-list img', 'click', function(){
            var arr = [];
            _this.selector.find('.upload-img-list img').each(function(){
                arr.push($(this).data());
            });

            if(typeof _this.opts.preView == "function"){
                var fileid = $(this).data('id');
                _this.opts.preView(fileid, arr);
            }
        });
    };

    /**
     * 图片上传
     * @param filesArr
     * @returns {boolean}
     */
    Upload.prototype.uploadFile = function(filesArr){
        var l = filesArr.length;
        if(!l){ return; }
        $('.upload-input-file').val('');
        var _this = this;
        var limit = _this.opts.limit;
        for(var i=0; i<l; i++){
            if(filesArr[i] == undefined){
                return false;
            }
            var type = filesArr[i].type.substr(filesArr[i].type.lastIndexOf('/') + 1);
            if (limit.length && limit.indexOf(type) === -1) {
                _this.alerts({msg:'文件格式不支持！'});
                return;
            }

            if (filesArr[i].size > _this.opts.maxSize) {
                _this.alerts({msg:'单张图片最大支持'+ _this.opts.maxSize/1024/1024 +'M！'});
                return;
            }
            if (filesArr[i].size == 0) {
                _this.alerts({msg:'图片不能为空！'});
                return;
            }

            var fileData = new FormData();
            fileData.append('file', filesArr[i]);

            if(filesArr[i].type && filesArr[i].type.indexOf('pdf') > -1){
                var url = "/api/v1/sys/files/upload/file";
            }else if (filesArr[i].type && filesArr[i].type.indexOf('image') > -1){
                var url = "/api/v1/sys/files/upload/pic";
            } else {
                _this.alerts({msg:'文件格式不支持！'});
                return;
            }
            $.ajax({
                type:"POST",
                url:url,
                data: fileData,
                processData: false,
                contentType: false,
                success:function(res){
                    //需要重新组织已上传图片结构。并且将返回的数据绑定到节点上。
                    if(res.errorCode === 0){
                        _this.redom(res.data);
                        _this.updateStatus();
                    }
                }
            });
        }
    };

    /**
     * 上传成功之后执行DOM操作
     */
    Upload.prototype.redom = function(data){
        if(!data || (typeof data == 'object' && JSON.stringify(data) == '{}')){ return; }

        var _this = this;

        if(_this.opts.multiple){

            var src = data.path;
            switch(data.type){
                case 'image/tiff': src = '/images/tiff-file.svg';break;
                case 'application/pdf': src = '/images/pdf-file.svg';break;
            }

            var html = '<div class="upload-img-list">' +
                '<img data-id="'+ data.id +'" data-name="'+ data.name +'" data-path="'+ data.path +'" data-type="'+ data.type +'" src="'+ src +'">' +
                '<div class="upload-del"></div></div>';

            _this.selector.find('.upload-img-box').append(html);
        }else{
            _this.selector.find('.upload-btn-box').children('img').attr('src',data.path).data(data);
        }
    };

    /**
     * 多组图上传，获取当前已上传的图片
     */
    Upload.prototype.uploadedNum = function(){
        var _this = this,
            retVal = 0;

        if(_this.opts.multiple){
            retVal = _this.selector.find('.upload-img-list').length;
        }

        return retVal;
    };

    /**
     * 上传完成后更新上传状态
     */
    Upload.prototype.updateStatus = function(){
        var _this = this;
        if(_this.opts.multiple){
            if(_this.uploadedNum() >= _this.opts.max){
                _this.selector.find('.upload-btn-box').hide();
            }else{
                _this.selector.find('.upload-btn-box').show();
            }
        }
    };

    /**
     * 获取图片信息
     */
    Upload.prototype.getImgInfo = function(){
        var _this = this;


        if(_this.opts.multiple){
            var ret = [];
            _this.selector.find('.upload-img-list img').each(function(){
                ret.push($(this).data());
            });
        }else{
            var ret = {};
            ret = _this.selector.find('.upload-btn-box img').data();
        }

        return ret;
    };

    /**
     * 弹出提示框
     */
    Upload.prototype.alerts = function(config){
        if($("#prompt").length > 0) { $("#prompt").remove(); }
        var html = '';
        html += '<div id="prompt">';
            html += '<div class="prompt-box warning">';
                html += '<div class="prompt-warning-icon"></div>';
                html += '<div class="msgStyle">' + config.msg + '</div>';
                html += '<div class="prompt-close-btn"></div>';
            html += '</div>';
        html += '</div>';
        $('body').append(html);

        $('#prompt .prompt-close-btn').click(function(){
            $('#prompt').remove();
        });
    };

    module.exports = new Upload;
})();